package com.dotstone.chipism.activity;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;
import com.umeng.analytics.MobclickAgent;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class RewardActivity extends BaseActivity {
	private LinearLayout mBackL;
	// private Button mSubmitBtn;
	private Button mCashBtn;
	private Button mCash1Btn;
	private TextView mStatusBar;
	private TextView mRewardTv;
	private int reward;
	private Dialog dialog;
	private Dialog dialog1;
	private Dialog dialog2;
	private Button mOk;
	private EditText mCashEdit;
	private String account;
	private int reward1;
	private String pwd;
	private EditText mAccountEdit;
	private EditText mPwdEd;
	private SVProgressHUD mSVProgressBar;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;
		case R.id.cash_btn:
			// ToastShow.Show(getApplicationContext(), "尚待完善");
			String shopToken = (String) SPUtils.get(getApplicationContext(), "shopToken", "");
			if (shopToken != null && !shopToken.equals("")) {
				showPathDialog();
			} else {
				ToastShow.Show(getApplicationContext(), "第三方异常");
			}
			break;
		case R.id.cash1_btn:
			ToastShow.Show(getApplicationContext(), "尚待完善");
			break;
		case R.id.wechat:
			ToastShow.Show(getApplicationContext(), "公测阶段，该功能暂未开放");
			break;
		case R.id.paypal:
			dialog.dismiss();
			showInfoDialog(2);
			break;
		case R.id.bank:
			ToastShow.Show(getApplicationContext(), "公测阶段，该功能暂未开放");
			break;
		default:
			break;
		}
	}

	private void showPathDialog() {
		dialog = new Dialog(RewardActivity.this, R.style.popupDialog3);
		dialog.setContentView(R.layout.dialog_path);
		LinearLayout wechat = (LinearLayout) dialog.findViewById(R.id.wechat);
		LinearLayout paypal = (LinearLayout) dialog.findViewById(R.id.paypal);
		LinearLayout bank = (LinearLayout) dialog.findViewById(R.id.bank);
		wechat.setOnClickListener(this);
		paypal.setOnClickListener(this);
		bank.setOnClickListener(this);
		dialog.show();
	}

	private void showInfoDialog(int path) {
		dialog1 = new Dialog(RewardActivity.this, R.style.popupDialog3);
		dialog1.setContentView(R.layout.dialog_cash_info);
		TextView pathTv = (TextView) dialog1.findViewById(R.id.path_tv);
		mAccountEdit = (EditText) dialog1.findViewById(R.id.account_edit);
		mCashEdit = (EditText) dialog1.findViewById(R.id.cash_edit);
		TextView mIntegrationTv = (TextView) dialog1.findViewById(R.id.integration_tv);
		Button mAllBtn = (Button) dialog1.findViewById(R.id.all);
		mOk = (Button) dialog1.findViewById(R.id.confirm_btn);
		mOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 判断是手机还是电子邮箱
				account = mAccountEdit.getText().toString();
				if (Util.isEmail(account) || Util.isMobile(account)) {
					dialog1.dismiss();
					reward1 = Integer.parseInt(mCashEdit.getText().toString());
					showPwdDialog(mCashEdit.getText().toString());
				} else {
					ToastShow.Show(getApplicationContext(), "帐号不符合规格");
				}
			}
		});
		switch (path) {
		case 1:
			pathTv.setText("提现至微信钱包");
			break;
		case 2:
			pathTv.setText("提现至支付宝钱包");
			break;
		case 3:
			pathTv.setText("提现至银行卡");
			break;

		default:
			break;
		}
		mIntegrationTv.setText("可用积分：" + reward);
		mCashEdit.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				if (!s.toString().isEmpty()) {
					int value = Integer.valueOf(s.toString());
					if (value < 0) {
						mCashEdit.setText("");
						mOk.setClickable(false);
						mOk.setBackgroundResource(R.drawable.bg_conner_light_gray1);
						mOk.setTextColor(Color.parseColor("#777777"));
					} else if (value > reward) {
						mCashEdit.setText(reward + "");
						mCashEdit.setSelection(mCashEdit.getText().toString().length());
						mOk.setClickable(true);
						mOk.setBackgroundResource(R.drawable.selector_demo);
						mOk.setTextColor(Color.parseColor("#ffffff"));
					} else {
						mOk.setClickable(true);
						mOk.setBackgroundResource(R.drawable.selector_demo);
						mOk.setTextColor(Color.parseColor("#ffffff"));
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		mAllBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mCashEdit.setText(reward + "");
				mOk.setClickable(true);
				mOk.setBackgroundResource(R.drawable.selector_demo);
				mOk.setTextColor(Color.parseColor("#ffffff"));
			}
		});
		dialog1.show();
	}

	private void showPwdDialog(String cash) {
		dialog2 = new Dialog(RewardActivity.this, R.style.popupDialog3);
		dialog2.setContentView(R.layout.dialog_pwd);
		TextView cashTv = (TextView) dialog2.findViewById(R.id.cash_tv);
		mPwdEd = (EditText) dialog2.findViewById(R.id.pwd_ed);
		Button mOkBtn = (Button) dialog2.findViewById(R.id.ok);
		cashTv.setText("提现金额：" + cash);
		mOkBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String pwd = (String) SPUtils.get(getApplicationContext(), "pwd", "");
				String pwd1 = mPwdEd.getText().toString();
				Log.i("wmy", pwd + " " + pwd1);
				if (pwd1 != null && !pwd1.equals("") && pwd.equals(pwd1)) {
					// dialog2.dismiss();
					mSVProgressBar = new SVProgressHUD(RewardActivity.this);
					mSVProgressBar.showWithStatus("正在提交");
					String phone = (String) SPUtils.get(getApplicationContext(), "user_name", "");
					login(phone, pwd);
					// updateReward();
				} else {
					ToastShow.Show(getApplicationContext(), "密码不正确");
					dialog2.dismiss();
				}
			}

		});
		dialog2.show();
	}

	private void login(final String name, final String pwd) {

		if (NetUtil.isNetworkAvailable(this)) {
			RequestParams params = new RequestParams(HttpURL.LOGIN_URL);
			params.setAsJsonContent(true);

			JSONObject obj = new JSONObject();
			try {
				obj.put("key", "10000");
				obj.put("mobile", name);
				obj.put("password", pwd);
				obj.put("reqAddress", "未知");
				obj.put("reqOs", "3");
				obj.put("requestTime", "" + System.currentTimeMillis());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());

			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("test", "login=" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);

						int resultCode = jsonObject.optInt("resultCode");
						MobclickAgent.onProfileSignIn(name);
						int user_id = jsonObject.getJSONObject("data").getJSONObject("userLogin").optInt("userId");
						String token = jsonObject.getJSONObject("data").getJSONObject("userLogin").optString("token");
						String shopToken = jsonObject.getJSONObject("data").getJSONObject("userLogin")
								.optString("shopToken");
						SocketManager.getInstance().user_id = user_id + "";
						SocketManager.getInstance().token = token;
						SPUtils.put(getApplicationContext(), "user_id", user_id + "");
						try {
							String iconUrl = jsonObject.getJSONObject("data").getJSONObject("userInfo")
									.optString("iconUrl");
							String userName = jsonObject.getJSONObject("data").getJSONObject("userInfo")
									.optString("userName");
							SPUtils.put(getApplicationContext(), "iconUrl", iconUrl);
							SPUtils.put(getApplicationContext(), "userName", userName);
						} catch (Exception e) {

						}
						SPUtils.put(getApplicationContext(), "pwd", pwd);
						SPUtils.put(getApplicationContext(), "user_name", name);
						SPUtils.put(getApplicationContext(), "user_id", user_id + "");
						SPUtils.put(getApplicationContext(), "token", token);
						SPUtils.put(getApplicationContext(), "shopToken", shopToken);
						updateReward();
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onError(Throwable ex, boolean isOnCallback) {

				}

				@Override
				public void onCancelled(CancelledException cex) {
				}

				@Override
				public void onFinished() {
				}
			});
		} else {
			Toast toast = Toast.makeText(getApplicationContext(), R.string.nonetwork, Toast.LENGTH_SHORT);
			toast.show();
		}

	}

	private void updateReward() {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams(HttpURL.HANDLE_REWARD_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("integral", "-" + reward1);
			obj.put("payee_account", account);
			obj.put("shopToken", (String) SPUtils.get(getApplicationContext(), "shopToken", ""));
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(RewardActivity.this, "token", ""));
			Log.e("wmy", "update reward = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("wmy", "update reward result= " + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					String value = jsonObject.getString("resultCode");
					if (value.equals("1")) {
						if (mSVProgressBar.isShowing()) {
							mSVProgressBar.dismiss();
						}
						ToastShow.Show(getApplicationContext(), "提现成功");
						dialog2.dismiss();
						getReward();
					} else {
						String errorMsg = jsonObject.optString("errorMsg");
						ToastShow.Show(getApplicationContext(), "提现失败:" + errorMsg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}
		});

	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_reward;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mBackL = $(R.id.back_layout);
		// mSubmitBtn = $(R.id.nextstep);
		// mSubmitBtn.setVisibility(View.VISIBLE);
		mStatusBar = $(R.id.tv_statusBar_mian);
		mCashBtn = $(R.id.cash_btn);
		mCash1Btn = $(R.id.cash1_btn);
		mRewardTv = $(R.id.code_tv);
		boolVersion();
		mBackL.setOnClickListener(this);
		mCashBtn.setOnClickListener(this);
		mCash1Btn.setOnClickListener(this);
		getReward();
	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	private void getReward() {
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			if (!Util.isLogin(getApplicationContext())) {
				return;
			}
			RequestParams params = new RequestParams(HttpURL.GET_REWARD_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("key", "10000");
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
				Log.d("test", " get all order = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("wmy", "get all order =" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");

						if (resultCode.equals("1")) {
							reward = jsonObject.getInt("data");
							mRewardTv.setText(reward + getString(R.string.integral));
						} else if (resultCode.equals("10003")) {

						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}
	}

}
